package com.xsmart.goods.services;

import com.baomidou.mybatisplus.plugins.Page;
import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.goods.dao.GoodsCategoryDao;
import org.apache.commons.collections.MapUtils;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.Request;

import java.lang.reflect.Array;
import java.util.*;

/**
 * @author stom
 * @version V1.0.0
 */

@Service
public class GoodsCategoryService {
    @Autowired
    GoodsCategoryDao goodsCategoryDao;

    /**
     * 查询商品类型
     *
     * @param requestBean 请求对象
     * @return 返回对象
     */
    public ResponseBean queryGoodsCategory(RequestBean requestBean) {
        int currentPage = requestBean.getRequestParamInteger("currentPage", 1);
        int pageSize = requestBean.getRequestParamInteger("pageSize", 10);
        String cat_name = requestBean.getRequestParamString("cat_name");
        Integer cat_sts = requestBean.getRequestParamInteger("cat_sts");
        Map<String, Object> goodsCategoryMap = new HashMap<>();
        goodsCategoryMap.put("cat_name", cat_name);
        goodsCategoryMap.put("cat_sts", cat_sts);
        ResponseBean responseBean = requestBean.getResponseBean();
        Page<Map<String, Object>> page = new Page<>(currentPage, pageSize);
        List<Map<String, Object>> list = new ArrayList<>();
        if(cat_name!=null||cat_sts!=null){
            list = goodsCategoryDao.queryGoodsCategoryPageWithoutParentId(page, goodsCategoryMap);
            getChildren(list,null);
            Map<String, Object> listMap = new HashMap<>();
            if(list.size()>0){
                Iterator<Map<String, Object>> itList = list.listIterator();
                listMap = itList.next();
                String parentNode=queryParentNode(MapUtils.getInteger(listMap,"cat_id"),null);
                listMap.put("parent_node",parentNode);
                list.clear();
                list.add(listMap);
           }
            page.setRecords(list);
        }else {
            list = goodsCategoryDao.queryGoodsCategoryPage(page, goodsCategoryMap);
            getCategoryChildren(list);
        }
        page.setRecords(list);
        responseBean.addResultPageItem("goodsCategoryList", page);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**获得子节点
     * @param list
     * @param pcategory
     */
    private void getChildren(List<Map<String, Object>> list, Map<String, Object> pcategory) {
        for (Map<String, Object> childrenListMap : list) {
            String parentsNode=queryParentNode(MapUtils.getInteger(childrenListMap,"cat_id"),null);
            childrenListMap.put("parent_node",parentsNode);
            List<Map<String, Object>> childrenList = goodsCategoryDao.queryGoodsCategory(MapUtils.getLong(childrenListMap, "cat_id"));
            if (childrenList.size() > 0) {
                childrenListMap.put("children", childrenList);
                getChildren(childrenList, childrenListMap);
            }
        }
    }


    /**查找父节点
     * @param requestBean
     * @return
     */
    public ResponseBean findParentNode(RequestBean requestBean) {
        Long catId = requestBean.getRequestParamLong("cat_id");
        String type=requestBean.getRequestParamString("type");
        Map<String, Object> goodsCategoryMap = new HashMap<>();
        goodsCategoryMap.put("cat_id", catId);
        ResponseBean responseBean = requestBean.getResponseBean();
        List<Map<String, Object>> parentNodeList=new ArrayList<>();
        Map<String, Object> rootNode=new HashMap<>();
        rootNode.put("value",1);
        rootNode.put("label","顶级分类");
        parentNodeList.add(rootNode);
        List<Map<String, Object>> parentNode = goodsCategoryDao.queryGoodsCategory(null);
        if(type!=null&&type.equals("all")){
            getNodeChildren(parentNode, catId);
        }else{
            getCategoryNodeChildren(parentNode, catId);
        }
         rootNode.put("children",parentNode);
        responseBean.addResultItem("parentCategoryList", parentNodeList);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 查找父节点
     * @param requestBean
     * @return
     */
    public ResponseBean findParentId(RequestBean requestBean) {
        Integer catId = requestBean.getRequestParamInteger("cat_id");
        ResponseBean responseBean = requestBean.getResponseBean();
        String parentNode=queryParentNode(catId,null);
        responseBean.addResultItem("pNode", parentNode);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 查找父节点
     * @param catId 商品分类id
     * @param parentNode 父id,
     * @return
     */
    private String queryParentNode(Integer catId, String parentNode) {
        parentNode=parentNode==null?String.valueOf(catId):catId+","+parentNode;
        Map<String, Object> pList = goodsCategoryDao.queryPGoodsCategory(catId);
        int parentId=MapUtils.getIntValue(pList,"parent_id",1);
        if(parentId==1){
            parentNode = "1" + "," + parentNode;
            return parentNode;
        }else{
            return queryParentNode(parentId,parentNode);
        }
    }

    /**
     * 添加分类
     *
     * @param requestBean 请求对象
     * @return 返回结果
     */
    public ResponseBean addGoodsCategory(RequestBean requestBean) {
        String[][] files = new String[][]{{"cat_name", ""},
                {"cat_sts", "1"},
                {"keywords", ""},
                {"cat_desc", ""},
                {"parent_id", "1"},
                {"sort_order", "100"},
                {"template_file", ""},
                {"show_in_nav", "1"},
                {"is_show", "1"},
                {"grade", "100"},
                {"filter_attr", ""},
                {"style_icon", ""},
                {"cat_icon", ""},
                {"pinyin_keyword", ""},
                {"cat_alias_name", ""},
                {"touch_icon", ""}};
        Map<String, Object> goodsCategoryMap = new HashMap<>();
        for (String[] file : files) {
            Object val = requestBean.getRequestParam(file[0]);
            if (val == null) {
                //传递过来的值如果为空，就设置默认值
                goodsCategoryMap.put(file[0], file[1]);
            } else {
                //不为空，则设置成传递过来的值
                goodsCategoryMap.put(file[0], requestBean.getRequestParam(file[0]));
            }
        }
        goodsCategoryMap.put("goods_id", "3");
        goodsCategoryMap.put("cat_id", "3");
        goodsCategoryMap.put("test", "asdfasd");
        ResponseBean responseBean = requestBean.getResponseBean();
        int addNum = goodsCategoryDao.addGoodsCategory(goodsCategoryMap);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 删除
     *
     * @param requestBean
     * @return
     */
    public ResponseBean delGoodsCategory(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        long catId = requestBean.getRequestParamLong("cat_id");
        delCategoryNodeChildren(catId);
//        goodsCategoryDao.delGoodsCategory(catId);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 修改
     *
     * @param requestBean
     * @return
     */
    public ResponseBean modGoodsCategory(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        String cat_name = requestBean.getRequestParamString("cat_name");
        // 分类别名
        String cat_alias_name = requestBean.getRequestParamString("cat_alias_name");
        //父分类
        String parent_id = requestBean.getRequestParamString("parent_id");
        //关键字
        String keywords = requestBean.getRequestParamString("keywords");
        //分类显示顺序
        Integer sort_order = requestBean.getRequestParamInteger("sort_order");
        //状态栏
        Integer cat_sts = requestBean.getRequestParamInteger("cat_sts");
        //导航栏显示
        Integer show_in_nav = requestBean.getRequestParamInteger("show_in_nav");
        //前台页面显示
        Integer is_show = requestBean.getRequestParamInteger("is_show");
        //分类描述
        String cat_desc = requestBean.getRequestParamString("cat_desc");
        //价格分级
        Integer grade = requestBean.getRequestParamInteger("grade");
        //拼音关键字  类型是text 超长文本
        String pinyin_keyword = requestBean.getRequestParamString("pinyin_keyword");
        Integer cat_id = requestBean.getRequestParamInteger("cat_id");
        Map<String, Object> goodsCategoryMap = new HashMap<>();
        goodsCategoryMap.put("cat_id", cat_id);
        goodsCategoryMap.put("cat_name", cat_name);
        goodsCategoryMap.put("cat_alias_name", cat_alias_name);
        goodsCategoryMap.put("parent_id", parent_id);
        goodsCategoryMap.put("keywords", keywords);
        goodsCategoryMap.put("sort_order", sort_order);
        goodsCategoryMap.put("cat_sts", cat_sts);
        goodsCategoryMap.put("show_in_nav", show_in_nav);
        goodsCategoryMap.put("is_show", is_show);
        goodsCategoryMap.put("cat_desc", cat_desc);
        goodsCategoryMap.put("grade", grade);
        goodsCategoryMap.put("pinyin_keyword", pinyin_keyword);
        int num = goodsCategoryDao.modGoodsType(goodsCategoryMap);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 获取子分类
     *
     * @param list 分类
     */
    private void getCategoryChildren(List<Map<String, Object>> list) {
        getCategoryChildren(list, null);
    }

    /**
     * 获取子分类
     * @param list 分类
     * @param pcategory 父级节点
     */
    private void getCategoryChildren(List<Map<String, Object>> list, Map<String, Object> pcategory) {
        for (Map<String, Object> category : list) {
            if (pcategory != null && pcategory.containsKey("parent_node")) {
                category.put("parent_node", MapUtils.getString(pcategory, "parent_node", "") + "," + MapUtils.getString(category, "parent_id", ""));
            } else {
                category.put("parent_node", MapUtils.getString(category, "parent_id", ""));
            }

            List<Map<String, Object>> childrenList = goodsCategoryDao.queryGoodsCategory(MapUtils.getLong(category, "cat_id"));
            if (childrenList.size() > 0) {
                category.put("children", childrenList);
                getCategoryChildren(childrenList, category);
            }
        }
    }

    /**获取子分类
     * @param list
     * @param catId
     */
    private void getNodeChildren(List<Map<String, Object>> list, Long catId) {
        Iterator<Map<String, Object>> itList = list.listIterator();
        while (itList.hasNext()) {
            Map<String, Object> category = itList.next();
            Long ccatId = MapUtils.getLong(category, "cat_id");
                String catName = MapUtils.getString(category, "cat_name");
                category.clear();
                category.put("label", catName);
                category.put("value", ccatId);
                List<Map<String, Object>> childrenList = goodsCategoryDao.queryGoodsCategory(ccatId);
                if (childrenList.size() > 0) {
                    category.put("children", childrenList);
                    getNodeChildren(childrenList, catId);
                }
        }
    }

    /**获取子分类
     * @param list
     * @param catId
     */
    private void getCategoryNodeChildren(List<Map<String, Object>> list, Long catId) {
        Iterator<Map<String, Object>> itList = list.listIterator();
        while (itList.hasNext()) {
            Map<String, Object> category = itList.next();
            Long ccatId = MapUtils.getLong(category, "cat_id");
            if (ccatId.equals(catId)) {
                itList.remove();
            } else {
                String catName = MapUtils.getString(category, "cat_name");
                category.clear();
                category.put("label", catName);
                category.put("value", ccatId);
                List<Map<String, Object>> childrenList = goodsCategoryDao.queryGoodsCategory(ccatId);
                if (childrenList.size() > 0) {
                    category.put("children", childrenList);
                    getCategoryNodeChildren(childrenList, catId);
                }
            }
        }
    }
    /*
    * 级联删除方法
    * */
    public void delCategoryNodeChildren(Long catId){
        List<Map<String, Object>> childrenNodeList=goodsCategoryDao.queryParentGoodsCategory(catId);
        if (childrenNodeList.size()>0){
            for (Map<String,Object> map:childrenNodeList){
                Long catChildrenId=MapUtils.getLong(map,"cat_id");
                delCategoryNodeChildren(catChildrenId);
            }
        }
        goodsCategoryDao.delGoodsCategory(catId);
    }
}
